package org.example.controller;

import org.example.common.CommonResult;
import org.example.dao.*;
import org.example.entity.Permission;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Description: 控制器类
 * Author: Amao
 * Date: 2023/5/23
 */

@RestController
public class DemoController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper UserRoleMapper;
    @Autowired
    private RoleMapper RoleMapper;
    @Autowired
    private RolePermissionMapper RolePermissionMapper;
    @Autowired
    private PermissionMapper PermissionMapper;

    @PostMapping("/login")
    public CommonResult<?> login(
            @RequestParam String username, @RequestParam String password, HttpSession session) {
        // 验证用户名密码
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            return CommonResult.error(50007, "登录失败，账号不存在");
        }
        if (!password.equals(user.getPassword())) {
            return CommonResult.error(50007, "登录失败，账号或密码不正确");
        }
        // 返回用户对应的角色和权限
        int userId = user.getId();
        int roleId = UserRoleMapper.selectRoleIdByUserId(userId);
        Role role = RoleMapper.selectRoleById(roleId);
        int permissionId = RolePermissionMapper.selectPermissionIdByRoleId(roleId);
        Permission permission = PermissionMapper.selectPermissionById(permissionId);
        // 利用session存储用户权限信息
        session.setAttribute("permission_id", permissionId);
        session.setAttribute("path", permission.getPath());
        System.out.println("测试set方法"+session.getAttribute("path"));
        return CommonResult.success(user.getName(), "登录成功，角色为" + role.getName()+"，权限为"+permission.getPath());
    }

    @GetMapping("/user/list")
    public CommonResult<List<User>> getUserList(@RequestParam String username, @RequestParam String password) {
        System.out.println("username: " + username + " password: " + password);
        User user = userMapper.selectByUsername(username);
        if(user == null) {
            return CommonResult.error(400, "用户不存在");
        }else{
            return CommonResult.success(userService.findAllUser(), "Welcome to the admin page!");
        }
    }

    @GetMapping("/user/info")
    public CommonResult<User> getUserByUsername(@RequestParam String username) {
        User user = userMapper.selectByUsername(username);
        if(user == null) {
            return CommonResult.error(400, "用户不存在");
        }else{
            return CommonResult.success(user, "查询成功");
        }
    }

}
